package com.siyoumi.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;

//AES加密解密
public class XAes {
    public static Map<String, Object> genKeyAndIv() {
        String iv = XApp.getUUID().substring(0, 16);
        String key = XApp.getUUID().substring(0, 24);

        return Map.of("iv", iv, "key", key);
    }

    public static String encrypt(String data, String secretKeyStr, String ivStr) throws Exception {
        IvParameterSpec iv = new IvParameterSpec(ivStr.getBytes(StandardCharsets.UTF_8));
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKeyStr.getBytes(StandardCharsets.UTF_8), "AES");

        return encrypt(data, secretKeySpec, iv);
    }

    public static String decrypt(String data, String secretKeyStr, String ivStr) throws Exception {
        IvParameterSpec iv = new IvParameterSpec(ivStr.getBytes(StandardCharsets.UTF_8));
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKeyStr.getBytes(StandardCharsets.UTF_8), "AES");

        return decrypt(data, secretKeySpec, iv);
    }

    /**
     * 加密数据
     *
     * @param data      待加密的数据
     * @param secretKey AES 密钥
     * @return Base64 编码的加密数据
     */
    public static String encrypt(String data, SecretKey secretKey, IvParameterSpec iv) throws Exception {
        // 初始化加密器，指定 AES/ECB/PKCS5Padding
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);

        // 加密
        byte[] decryptedBytes = cipher.doFinal(data.getBytes());

        // 返回解密后的字符串
        return Base64.getEncoder().encodeToString(decryptedBytes);
    }


    /**
     * 解密数据
     *
     * @param encryptedData Base64 编码的加密数据
     * @param key           AES 密钥
     * @return 解密后的原始数据
     */
    public static String decrypt(String encryptedData, SecretKey key, IvParameterSpec iv) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");

        cipher.init(Cipher.DECRYPT_MODE, key, iv);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }
}
